package com.demo;

import com.demo.controller.RequestRouter;
import com.demo.schedule.TaskScheduler;
import com.demo.schedule.UserCleanupTask;
import com.demo.util.TimeUtil;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class Main {
  public static void main(String[] args) throws IOException {
    int port = 8082;
    HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
    server.createContext("/", new RequestRouter());
    server.setExecutor(null);
    server.start();
    System.out.println("✅ Server started on port " + port);

    // 初始化定时任务
    initScheduledTasks();

    // 添加关闭钩子，确保关闭
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
      System.out.println("Shutting down application...");
      server.stop(0);
      TaskScheduler.getInstance().shutdown();
      System.out.println("Application shutdown complete");
    }));
  }

  private static void initScheduledTasks() {
    TaskScheduler scheduler = TaskScheduler.getInstance();

    // 每10分钟执行一次的用户清理任务
    ScheduledFuture<?> userCleanupTask = scheduler.scheduleAtFixedRate(
        new UserCleanupTask(),
        0,   // 初始延迟（立即开始）
        10,  // 每10分钟
        TimeUnit.MINUTES
    );

    // 每天凌晨2点执行的统计任务
    scheduler.scheduleAtFixedRate(
        () -> System.out.println("每日统计任务执行中..."),
        TimeUtil.calculateInitialDelay(2, 0), // 凌晨2点
        24, // 每天执行一次
        TimeUnit.HOURS
    );

    System.out.println("定时任务初始化完成");
  }
}